const express = require('express')
const router = express.Router()
const auth = require('../middleware/auth')
const printReservationService = require('../services/printReservationService')
const logger = require('../utils/logger')
const Joi = require('joi')

/**
 * @route GET /api/print/configs
 * @desc 获取打印配置
 * @access Public
 */
router.get('/configs', async (req, res) => {
  try {
    const configs = await printReservationService.getPrintConfigs()

    res.json({
      success: true,
      code: 200,
      message: '获取打印配置成功',
      data: configs
    })
  } catch (error) {
    logger.error('Get print configs failed:', error)
    res.status(500).json({
      success: false,
      code: 1005,
      message: '获取打印配置失败'
    })
  }
})

/**
 * @route POST /api/print/reservations
 * @desc 创建打印预约
 * @access Private
 */
router.post('/reservations', auth, async (req, res) => {
  try {
    // 验证请求参数
    const schema = Joi.object({
      fileId: Joi.number().integer().positive().required(),
      printOptions: Joi.object({
        paperSize: Joi.string().required(),
        colorType: Joi.string().required(),
        printQuality: Joi.string().required(),
        bindingType: Joi.string().optional(),
        duplex: Joi.boolean().optional(),
        pageRange: Joi.string().optional()
      }).required(),
      quantity: Joi.number().integer().min(1).max(100).default(1),
      notes: Joi.string().max(500).optional()
    })

    const { error, value } = schema.validate(req.body)
    if (error) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: error.details[0].message
      })
    }

    const userId = req.user.id
    const { fileId, printOptions, quantity, notes } = value

    // 创建预约
    const reservation = await printReservationService.createReservation(
      userId,
      fileId,
      printOptions,
      quantity
    )

    // 如果有备注，更新预约记录
    if (notes) {
      await printReservationService.updateReservationNotes(reservation.id, notes)
    }

    res.json({
      success: true,
      code: 200,
      message: '创建预约成功',
      data: reservation
    })
  } catch (error) {
    logger.error('Create print reservation failed:', error)
    res.status(400).json({
      success: false,
      code: 6001,
      message: error.message || '创建预约失败'
    })
  }
})

/**
 * @route GET /api/print/reservations
 * @desc 获取用户预约列表
 * @access Private
 */
router.get('/reservations', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const status = req.query.status || null

    // 验证分页参数
    if (page < 1 || limit < 1 || limit > 100) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: '无效的分页参数'
      })
    }

    const result = await printReservationService.getUserReservations(userId, page, limit, status)

    res.json({
      success: true,
      code: 200,
      message: '获取预约列表成功',
      data: result
    })
  } catch (error) {
    logger.error('Get user reservations failed:', error)
    res.status(500).json({
      success: false,
      code: 1005,
      message: '获取预约列表失败'
    })
  }
})

/**
 * @route GET /api/print/reservations/:id
 * @desc 获取预约详情
 * @access Private
 */
router.get('/reservations/:id', auth, async (req, res) => {
  try {
    const reservationId = parseInt(req.params.id)
    const userId = req.user.id

    if (!reservationId || isNaN(reservationId)) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: '无效的预约ID'
      })
    }

    const reservation = await printReservationService.getReservationDetail(reservationId)

    // 检查权限
    if (reservation.user.id !== userId) {
      return res.status(403).json({
        success: false,
        code: 1003,
        message: '无权限访问此预约'
      })
    }

    res.json({
      success: true,
      code: 200,
      message: '获取预约详情成功',
      data: reservation
    })
  } catch (error) {
    logger.error('Get reservation detail failed:', error)
    res.status(404).json({
      success: false,
      code: 1004,
      message: error.message || '预约不存在'
    })
  }
})

/**
 * @route POST /api/print/reservations/:id/cancel
 * @desc 取消预约
 * @access Private
 */
router.post('/reservations/:id/cancel', auth, async (req, res) => {
  try {
    const reservationId = parseInt(req.params.id)
    const userId = req.user.id

    if (!reservationId || isNaN(reservationId)) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: '无效的预约ID'
      })
    }

    await printReservationService.cancelReservation(reservationId, userId)

    res.json({
      success: true,
      code: 200,
      message: '取消预约成功'
    })
  } catch (error) {
    logger.error('Cancel reservation failed:', error)
    res.status(400).json({
      success: false,
      code: 6002,
      message: error.message || '取消预约失败'
    })
  }
})

/**
 * @route POST /api/print/validate-code
 * @desc 验证预约码
 * @access Public
 */
router.post('/validate-code', async (req, res) => {
  try {
    const schema = Joi.object({
      reservationCode: Joi.string().required()
    })

    const { error, value } = schema.validate(req.body)
    if (error) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: error.details[0].message
      })
    }

    const { reservationCode } = value
    const reservation = await printReservationService.validateReservationCode(reservationCode)

    res.json({
      success: true,
      code: 200,
      message: '验证预约码成功',
      data: reservation
    })
  } catch (error) {
    logger.error('Validate reservation code failed:', error)
    res.status(400).json({
      success: false,
      code: 6003,
      message: error.message || '预约码验证失败'
    })
  }
})

/**
 * @route POST /api/print/confirm
 * @desc 确认预约（店员使用）
 * @access Public
 */
router.post('/confirm', async (req, res) => {
  try {
    const schema = Joi.object({
      reservationCode: Joi.string().required(),
      storeLocation: Joi.string().optional()
    })

    const { error, value } = schema.validate(req.body)
    if (error) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: error.details[0].message
      })
    }

    const { reservationCode, storeLocation } = value
    const reservation = await printReservationService.confirmReservation(reservationCode, storeLocation)

    res.json({
      success: true,
      code: 200,
      message: '确认预约成功',
      data: reservation
    })
  } catch (error) {
    logger.error('Confirm reservation failed:', error)
    res.status(400).json({
      success: false,
      code: 6004,
      message: error.message || '确认预约失败'
    })
  }
})

/**
 * @route POST /api/print/complete
 * @desc 完成预约（店员使用）
 * @access Public
 */
router.post('/complete', async (req, res) => {
  try {
    const schema = Joi.object({
      reservationCode: Joi.string().required()
    })

    const { error, value } = schema.validate(req.body)
    if (error) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: error.details[0].message
      })
    }

    const { reservationCode } = value
    const reservation = await printReservationService.completeReservation(reservationCode)

    res.json({
      success: true,
      code: 200,
      message: '完成预约成功',
      data: reservation
    })
  } catch (error) {
    logger.error('Complete reservation failed:', error)
    res.status(400).json({
      success: false,
      code: 6005,
      message: error.message || '完成预约失败'
    })
  }
})

/**
 * @route POST /api/print/calculate-cost
 * @desc 计算打印费用
 * @access Private
 */
router.post('/calculate-cost', auth, async (req, res) => {
  try {
    const schema = Joi.object({
      fileId: Joi.number().integer().positive().required(),
      printOptions: Joi.object({
        paperSize: Joi.string().required(),
        colorType: Joi.string().required(),
        printQuality: Joi.string().required(),
        bindingType: Joi.string().optional()
      }).required(),
      quantity: Joi.number().integer().min(1).max(100).default(1)
    })

    const { error, value } = schema.validate(req.body)
    if (error) {
      return res.status(400).json({
        success: false,
        code: 1001,
        message: error.details[0].message
      })
    }

    const { fileId, printOptions, quantity } = value

    // 获取文件信息
    const { File } = require('../models')
    const file = await File.findOne({
      where: {
        id: fileId,
        user_id: req.user.id,
        status: 1
      }
    })

    if (!file) {
      return res.status(404).json({
        success: false,
        code: 1004,
        message: '文件不存在'
      })
    }

    // 计算积分消耗
    const pointsCost = await printReservationService.calculatePointsCost(file, printOptions, quantity)

    res.json({
      success: true,
      code: 200,
      message: '计算费用成功',
      data: {
        pointsCost,
        totalPages: (file.page_count || 1) * quantity,
        quantity
      }
    })
  } catch (error) {
    logger.error('Calculate print cost failed:', error)
    res.status(400).json({
      success: false,
      code: 6006,
      message: error.message || '计算费用失败'
    })
  }
})

module.exports = router